const {
    hgetall,
    lrange,
    hlen,
    easyPushWechatMsgAdmin,
    sleep,
    hdel,
} = require('./util');
const sdate = require('silly-datetime');
const { logger } = require('./util');

const {
    readTask,
} = require('./ti_logic_read_task');

const main = async () => {
    while (1) {
        const today = sdate.format(new Date(), 'YYYY-MM-DD');
        const serial_data_key = 'serial_data_'+ today;
        const data = await hgetall(serial_data_key);

        const success_log_key = 'success_log_'+ today;

        const data2 = await lrange(success_log_key, 0, 1000);

        const count = await hlen(serial_data_key);

        logger('count', count);

        //logger(data2);

        //logger(data);

        let expire_list = [];

        let now_time = new Date().getTime();

        let tasks = await readTask(1,300);

        //logger(tasks);

        let serial_list = [];

        let serial_list_task = [];


        for(var key in tasks){
            serial = tasks[key].serial;
            serial_list_task.push(serial);
        }

        let need_del_serial_list = [];

        //logger('serial_list_task', serial_list_task);

        

        for(var key in data){

        	let tmp_data = JSON.parse(data[key]);

        	let tmp_time = (tmp_data['last_check_time']);

        	tmp_time = new Date(tmp_time).getTime();

            let serial = tmp_data.serial;

            //logger('serial', serial);

            serial_list.push(serial);

            //logger(now_time-tmp_time);

            //logger(tmp_data);

        	if(now_time - tmp_time>70*1000){
        		expire_list.push(data[key]);
                //if(tmp_data['worker'] == '机器2')
                logger(tmp_data);

                //if(tmp_data['serial'] == 'LSF0108RKSR'){
                //    logger(tmp_data);
                //}
        	}

        	if(tmp_data['worker'] == '机器1'){
        		//logger(tmp_data);
        	}

            if(serial_list_task.indexOf(serial)<0){
                need_del_serial_list.push(serial);
            }
        }

        //logger(need_del_serial_list);

        for(var key in need_del_serial_list){
            //logger('need_del_serial_list', serial_data_key+' '+need_del_serial_list[key]);
            await hdel(serial_data_key, need_del_serial_list[key], '');
        }

        for(var key in tasks){
            serial = tasks[key].serial;
            if(serial_list.indexOf(serial)<0){
                //logger('serial', serial);
            }
        }

        let expire_count = expire_list.length;

        logger('expire_count', expire_count);

        if(expire_count >130){
            await easyPushWechatMsgAdmin('异常进程数'+expire_count);
        }

        await sleep(60000);
    }

    //logger(expire_list);
}

main()